// 积分任务管理器模块
// 使用全局函数（由 core.js 提供）
const { getUserInfo, setUserInfo } = window;

/**
 * 计算并显示到次日凌晨的倒计时
 */
function updateNextCheckinCountdown() {
    const countdownElement = document.getElementById('next-checkin-countdown');
    if (!countdownElement) return;
    
    // 计算到次日凌晨的时间差
    function calculateTimeRemaining() {
        const now = new Date();
        const tomorrow = new Date(now);
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(0, 0, 0, 0);
        
        const diff = tomorrow - now;
        const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
        const minutes = Math.floor((diff / 1000 / 60) % 60);
        const seconds = Math.floor((diff / 1000) % 60);
        
        return { hours, minutes, seconds };
    }
    
    // 更新显示
    function updateDisplay() {
        const time = calculateTimeRemaining();
        countdownElement.textContent = `下次签到: ${time.hours.toString().padStart(2, '0')}:${time.minutes.toString().padStart(2, '0')}:${time.seconds.toString().padStart(2, '0')}`;
        
        // 如果倒计时结束，刷新页面或重新检查签到状态
        if (time.hours === 0 && time.minutes === 0 && time.seconds === 0) {
            location.reload();
        }
    }
    
    // 立即更新一次
    updateDisplay();
    
    // 每秒更新一次
    return setInterval(updateDisplay, 1000);
}

/**
 * 绑定积分任务按钮事件
 */
export function bindPointsTaskListeners() {
    // 启动倒计时
    let countdownInterval = updateNextCheckinCountdown();
    
    // 每日签到按钮
    const dailyCheckinBtn = document.getElementById('daily-checkin-btn');
    if (dailyCheckinBtn) {
        dailyCheckinBtn.addEventListener('click', function() {
            const user = getUserInfo();
            if (!user) return;
            
            // 检查是否已经签到过了
            const today = new Date().toDateString();
            if (user.lastCheckin === today) {
                // 已经签到过了
                showPointsNotification('今日已签到', '您今天已经签到过了，明天再来吧！', 'info');
                return;
            }
            
            // 执行签到操作
            const pointsGained = 10;
            const updatedUser = {
                ...user,
                points: (user.points || 0) + pointsGained,
                lastCheckin: today
            };
            
            // 保存更新后的用户信息
            setUserInfo(updatedUser);
            
            // 更新页面显示
            updateProfileDisplay(updatedUser);
            
            // 显示成功通知
            showPointsNotification('签到成功', `恭喜您获得${pointsGained}积分奖励！`, 'success');
            
            // 更新按钮状态为已签到
            dailyCheckinBtn.textContent = '已签到';
            dailyCheckinBtn.disabled = true;
            dailyCheckinBtn.classList.add('opacity-50', 'cursor-not-allowed');
        });
        
        // 初始化检查签到状态
        const user = getUserInfo();
        if (user && user.lastCheckin === new Date().toDateString()) {
            dailyCheckinBtn.textContent = '已签到';
            dailyCheckinBtn.disabled = true;
            dailyCheckinBtn.classList.add('opacity-50', 'cursor-not-allowed');
        }
    }
    
    // 添加清理函数，在页面卸载时清除定时器
    window.addEventListener('beforeunload', function() {
        if (countdownInterval) {
            clearInterval(countdownInterval);
        }
    });
    
    // 邀请好友按钮
    const inviteFriendBtn = document.getElementById('invite-friend-btn');
    if (inviteFriendBtn) {
        inviteFriendBtn.addEventListener('click', function() {
            const user = getUserInfo();
            // 创建临时输入框来复制邀请链接
            const tempInput = document.createElement('input');
            const inviteLink = `${window.location.origin}/register.html?ref=${encodeURIComponent(user.username)}`;
            tempInput.value = inviteLink;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand('copy');
            document.body.removeChild(tempInput);
            
            showPointsNotification('邀请链接已复制', '您的邀请链接已复制到剪贴板，快去分享给好友吧！', 'success');
        });
    }
    
    // 暂时没有活动按钮，HTML中不存在这个元素
}

/**
 * 显示积分相关通知
 * @param {string} title 通知标题
 * @param {string} message 通知内容
 * @param {string} type 通知类型
 */
export function showPointsNotification(title, message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'fixed top-20 right-4 bg-white rounded-lg shadow-lg p-4 max-w-xs z-50 transform transition-all duration-300 opacity-0 translate-x-10';
    
    // 设置通知颜色
    let iconClass = 'text-primary';
    let bgClass = 'bg-primary/10';
    if (type === 'success') {
        iconClass = 'text-success';
        bgClass = 'bg-success/10';
    } else if (type === 'error') {
        iconClass = 'text-danger';
        bgClass = 'bg-danger/10';
    } else if (type === 'warning') {
        iconClass = 'text-warning';
        bgClass = 'bg-warning/10';
    }
    
    // 设置通知内容
    notification.innerHTML = `
        <div class="flex items-start space-x-3">
            <div class="w-8 h-8 rounded-full flex items-center justify-center ${bgClass} ${iconClass}">
                <i class="fa fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : type === 'warning' ? 'exclamation' : 'info'}-circle"></i>
            </div>
            <div class="flex-1">
                <h4 class="font-medium text-gray-800">${title}</h4>
                <p class="text-gray-600 text-sm mt-1">${message}</p>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.remove('opacity-0', 'translate-x-10');
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.classList.add('opacity-0', 'translate-x-10');
        
        // 通知消失后移除元素
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

/**
 * 更新个人资料显示
 * @param {Object} user 更新后的用户信息
 */
export function updateProfileDisplay(user) {
    // 更新用户积分显示
    const userPointsEl = document.getElementById('profile-points');
    if (userPointsEl) {
        userPointsEl.textContent = user.points || 0;
    }
    
    // 更新其他可能需要更新的个人信息
    const profileUsername = document.getElementById('profile-username');
    if (profileUsername) {
        profileUsername.textContent = user.username || '小镇名称';
    }
}